package com.publicstaticdroid.g2l_interpreter_connect;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;

/**
 * Alerts interpreter of a new request and makes a dialog
 * asking if they will accept the interpretation request.
 * @author dvhc, Nathan Breit
 * 
 */
//NOTE: This dialog is self-dismissing. Using messages from the server has not been tested.
//due to the similarities with the wait for call activity some inheritance might be possible.
//i.e. ActivityWithTimedDialogs.java
//Maybe show a clock in the dialog as well
public class NeedAnInterpreter extends Activity
{
	private static final String LOG_TAG = "G2L InterpreterNeeded";
	
	private int MILLISECONDS_TO_WAIT = 1000 * 90;
	private Timer dialogTimer;
	
	private Date alertTime;
	
	private String replyTo;
	private int requestID;
	private String language;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.blank);
		
		if(!getIntent().hasExtra("requestID") || !getIntent().hasExtra("language"))
		{
			Log.e(LOG_TAG, "Missing extras");
			finish();
			return;
		}
		if(getIntent().getBooleanExtra("cancel", false)){
			Log.e(LOG_TAG, "Cancel extra is true.");
			//finish();
			//return;
		}
		
		replyTo = Constants.SERVER_PHONE; //This could be parameterized in the future if there are multiple servers.
		requestID = getIntent().getIntExtra("requestID", -1);
		language = getIntent().getStringExtra("language");
		
		alertTime = new Date();
		
		// Beep and blink to get interpreters attention.
		Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		// Vibrate for 500 milliseconds
		v.vibrate(500);
		playSound(getApplicationContext());
		
		showDialog(requestID);
	}
	//Method from:
	//http://stackoverflow.com/questions/2618182/how-to-play-ringtone-alarm-sound-in-android
	public void playSound(Context context) {
		try {
			Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			MediaPlayer mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setDataSource(context, soundUri);
			final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
			if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mMediaPlayer.setLooping(false);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
			}
		} catch (Exception e) {
			Log.e("G2L", "problem playing sound");
		}
	}
	protected Dialog onCreateDialog(int id)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		final SMSSender texter = new SMSSender(replyTo);
		
		builder.setTitle("G2L Interpreter Needed")
				.setMessage("Will you accept a " + language + " interpreting request now?")
				.setCancelable(true)
				.setPositiveButton("Yes", 
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{
								texter.sendAccept(requestID, alertTime.getTime(), new Date().getTime());
								cancelNotification();
								dialog.cancel();
								
								//Increment the requests accepted counter
								SharedPreferences settings = getSharedPreferences(Constants.PREFS_KEY, 0);
								SharedPreferences.Editor editor = settings.edit();
								editor.putInt("requestsAccepted", 1 + settings.getInt("requestsAccepted", 0));
								editor.commit();
								
								//Start a "wait for call activity"
								Intent makeCallIntent = new Intent(getApplicationContext(), WaitForCallActivity.class);
								makeCallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								makeCallIntent.putExtra("requestID", requestID);
								startActivity(makeCallIntent);
								finish();
							}
						})
				.setNegativeButton("No", 
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{
								texter.sendReject(requestID, alertTime.getTime(), new Date().getTime());
								cancelNotification();
								dialog.cancel();
								finish();
							}
						});
		AlertDialog alert = builder.create();
		alert.setOnCancelListener(new OnCancelListener()
		{
			@Override
			public void onCancel(DialogInterface arg0)
			{
				finish();	// ensure we don't leave an empty (transparent) screen with no dialog!
			}
		});
		Log.w(LOG_TAG, "New alert: request " + requestID + " for " + language + " interpreter");
		return alert;
	}
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        	
        	dialogTimer = new Timer();
        	
        	dialogTimer.schedule(new TimerTask() {
        		
    			@Override
    			public void run() {
    				runOnUiThread(new Runnable() {
    				
    	    			@Override
    	    			public void run() {
		    				Log.e("G2L", "Dialog timer expired.");
		    				removeDialog(requestID);
		    				finish();
    	    			}
    				});
    			}
    			
    		}, MILLISECONDS_TO_WAIT );
    		
    }
	private void cancelNotification()
	{
		dialogTimer.cancel();
		dialogTimer.purge();
		
		// TODO: Re-add this if we switch back to using notifications
		/*
		// Cancel existing status bar notification for this interpreting request
		NotificationManager notifier;
		notifier = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notifier.cancel(requestID);
		*/
	}
	@Override
	protected void onNewIntent(Intent intent) {
		if(requestID == intent.getIntExtra("requestID", -1)){
			if (intent.getBooleanExtra("cancel", false))	// if the request has been cancelled
			{
				Log.w(LOG_TAG, "Trying to cancel alert: request " + requestID);
				// TODO: This doesn't work.  No effect, and no error messages in the log.
				cancelNotification(); //Needed?
				removeDialog(requestID);
				finish();
			}
		}
		else{
			// This will happen when the interpreter gets another request before accepting the current one.
			// Then we end up ignoring the new request. (If we make an alert in the receiver that will still show up)
			// It might be better to queue them somehow in case the interpreter isn't chosen for the first request.
			// Using notifications has the advantage of allowing users to deal with multiple requests in a reasonable way.
			Log.e("G2L", "RequestID mismatch in NeedInterpreter: " + requestID + " vs " + intent.getIntExtra("requestID", -1));
		}
	}
}
